package com.weichai.app.page.home.viewmodel;

import android.text.TextUtils;
import android.widget.Toast;

import com.kunminx.architecture.ui.callback.UnPeekLiveData;
import com.weichai.app.arch.base.BaseViewModel;
import com.weichai.app.arch.http.ApiManager;
import com.weichai.app.arch.http.ApiSubscriber;
import com.weichai.app.arch.http.ApiTransformer;
import com.weichai.app.bean.BaseResult;
import com.weichai.app.bean.FaultCodeEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dev.utils.app.toast.ToastUtils;

public class FaultCodeVM extends BaseViewModel {
    public UnPeekLiveData<String> spnCode = new UnPeekLiveData<>();
    public UnPeekLiveData<String> fmiCode = new UnPeekLiveData<>();
    public UnPeekLiveData<List<String>> tabList = new UnPeekLiveData<>();
    public UnPeekLiveData<Map<String, List<FaultCodeEntity>>> tabMap = new UnPeekLiveData<>();

    public void search() {
        if (TextUtils.isEmpty(spnCode.getValue()) || TextUtils.isEmpty(fmiCode.getValue())) {
            ToastUtils.showToast("请输入故障码！", Toast.LENGTH_SHORT);
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("spnCode", spnCode.getValue());
        params.put("fmiCode", fmiCode.getValue());

        ApiManager.getInstance()
                .queryByFault(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<List<FaultCodeEntity>>(true, false, this) {
                    @Override
                    public void onSuccess(BaseResult<List<FaultCodeEntity>> result) {
                        if (null != result.data) {
                            List<String> ecuTypeList = new ArrayList<>();
                            for (FaultCodeEntity faultCodeEntity : result.data) {
                                if (!ecuTypeList.contains(faultCodeEntity.ecuType)) {
                                    ecuTypeList.add(faultCodeEntity.ecuType);
                                }
                            }
                            Map<String, List<FaultCodeEntity>> map = new HashMap<>();
                            for (String ecuType : ecuTypeList) {
                                List<FaultCodeEntity> faultCodeEntityList = new ArrayList<>();
                                for (FaultCodeEntity faultCodeEntity : result.data) {
                                    if (ecuType.equals(faultCodeEntity.ecuType)) {
                                        faultCodeEntityList.add(faultCodeEntity);
                                    }
                                }
                                map.put(ecuType, faultCodeEntityList);
                            }
                            tabMap.setValue(map);
                            tabList.setValue(ecuTypeList);
                        }
                    }
                });
    }
}
